<template>
  <div id="contianer">
    <div class="screen_model">
      <el-row :gutter="20">
        <el-col prop="name" :span="5">
          <el-input
            size="small"
            v-model="searchForm.name"
            placeholder="标签名称"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="5" prop="fieldId">
          <el-select
            size="small"
            style="width: 100%"
            v-model="searchForm.fieldId"
            clearable
            placeholder="领域标签"
          >
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :value="item.id"
              :label="item.labelName"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-select
            size="small"
            style="width: 100%"
            v-model="searchForm.user"
            clearable
            filterable
            allow-create
            default-first-option
            placeholder="创建人员"
            v-el-select-lazyloading="lazyloading"
            remote
                         :remote-method="remoteMethod"
                         @focus="searchFocus"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :value="item.id"
              :label="item.userName"
            ></el-option>
          </el-select>
        </el-col>
        <el-col
          :span="4"
          style="display: flex; justify-content: end; float: right"
        >
          <el-button type="primary" @click="getLabelList()" size="small"
            >查询</el-button
          >
          <el-button @click="resetSearch()" size="small">重置</el-button>
        </el-col>
      </el-row>
    </div>
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="addElements()">新增标签</el-button>
      <el-button type="primary" @click="batchImport">批量导入</el-button>
      <el-button type="primary" @click="batchExport" v-if="isAdmin">批量导出</el-button>
      <el-button type="primary" @click="templateFn">模版下载</el-button>
      <el-button type="primary" @click="batchDelete">批量删除</el-button>
    </div>

    <vxe-table
      resizable
      ref="labelVxeTable"
      border
      :tree-config="{ rowField: 'id', parentField: 'parentId' }"
      :data="tableData"
      :max-height="tableClientHeight"
      :checkbox-config="{ labelField: 'labelName' }"
      :loading="isLoading"
    >
      <vxe-column
        type="checkbox"
        tree-node
        field="labelName"
        title="标签名称"
      ></vxe-column>
      <vxe-column field="labelType" title="标签类型"></vxe-column>
      <vxe-column field="creator" title="创建人员"></vxe-column>
      <vxe-column field="createTime" title="创建时间"></vxe-column>
      <vxe-column field="" title="操作">
        <template slot-scope="scope">
          <!-- <el-link style="display: inline-block;margin-left: 10px;" @click="view(scope.row.id)">查看</el-link> -->
          <el-link
            type="primary"
            style="display: inline-block; margin-left: 10px"
            @click="addElements(scope.row, 'edit')"
            >修改</el-link
          >
          <el-link
            type="danger"
            style="display: inline-block; margin-left: 10px"
            @click="delFn(scope.row)"
            >删除</el-link
          >
        </template>
      </vxe-column>
    </vxe-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageNo"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      background
      layout="total, prev, pager, next, jumper"
    >
    </el-pagination>

    <!-- 新增标签 -->
    <el-dialog
      :title="elementsTitle"
      :visible.sync="elementsVisible"
      :close-on-click-modal="false"
      width="30%"
      center
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
      >
        <el-form-item label="标签名称" prop="labelName">
          <el-input
            v-model="ruleForm.labelName"
            placeholder="请输入标签名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="标签类型" prop="labelLevel">
          <el-select
            :disabled="elementsTitle == '修改标签'"
            v-model="ruleForm.labelLevel"
            placeholder="请选择标签类型"
            @change="changeLabel"
            ref="labelLevel"
          >
            <el-option
              v-for="item in labelList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="上级领域标签"
          prop="area"
          v-if="ruleForm.labelLevel === 2 || ruleForm.labelLevel === 3"
        >
          <el-select
            :disabled="elementsTitle == '修改标签'"
            v-model="ruleForm.area"
            placeholder="请选择上级领域标签"
            @change="changeArea"
          >
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :value="item.id"
              :label="item.labelName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="上级岗位标签"
          prop="post"
          v-if="ruleForm.labelLevel === 3"
        >
          <el-select
            :disabled="elementsTitle == '修改标签'"
            multiple
            v-model="ruleForm.post"
            placeholder="请选择上级岗位标签"
          >
            <el-option
              v-for="item in postList"
              :key="item.id"
              :value="item.id"
              :label="item.labelName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="elementsConfirm">确 定</el-button>
        <el-button @click="elementsVisibleClose">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 批量导入 -->
    <el-dialog
      title="批量导入"
      :visible.sync="batchImportVisible"
      width="30%"
      :close-on-click-modal="false"
      center
    >
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="batchImportConfirm">确 定</el-button>
        <el-button @click="batchImportClose">取 消</el-button>
      </span>
    </el-dialog>

    <importData
      ref="importData"
      @callParentMethod="getLabelList"
      :refreshData="getLabelList"
    ></importData>
  </div>
</template>
<script>
import importData from "./importData";
export default {
  data() {
    return {
      isLoading: true,
      elementsVisible: false,
      batchImportVisible: false,
      visibleDel: false,
      labelList: [
        {
          label: "领域标签",
          value: 1,
        },
        {
          label: "岗位标签",
          value: 2,
        },
        {
          label: "标签元素",
          value: 3,
        },
      ],
      elementsTitle: "新增标签",
      tableData: [],
      searchForm: {
        name: "",
        user: "",
        fieldId: "",
        pageNumber:1,
        pageSize:10,
        totalPage:0,
      },
      userForm:{
        name:''
      },
      areaList: [],
      postList: [],
      userList: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      ruleForm: {
        labelLevel: "",
        labelName: "",
        area: "",
        post: [],
      },
      rules: {
        labelName: [
          { required: true, message: "请输入标签名称", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        labelLevel: [
          { required: true, message: "请选择标签类型", trigger: "change" },
        ],
        area: [
          { required: true, message: "请选择上级领域标签", trigger: "change" },
        ],
        post: [
          { required: true, message: "请选择上级岗位标签", trigger: "change" },
        ],
      },
      // 存储展开的节点ID
      expandedNodeIds: new Set(),
    };
  },
  computed: {
    isAdmin() {
      return this.$store.state.user.isAdmin;
    },
    tableClientHeight() {
      let tableClientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      tableClientHeight = tableClientHeight - 340;
      return tableClientHeight;
    },
  },
  components: {
    importData,
  },
  mounted() {
    this.getLabelList();
    this.getUserList();
    this.getAreaData();
  },
  methods: {
    view() {},
    delFn(row) {
      console.log(row, "fff");

      this.$confirm(
        `确定删除${row ? "[" + row.labelName + "]" : "选中项"}吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        // if(row.hasChildren){
        //   this.$message.warning("当前节点下存在子节点,无法删除")
        //   return
        // }
        this.$http({
          url: "/knowledgeLabel/delete",
          method: "post",
          data: {
            id: row.id,
          },
        }).then(({ data }) => {
          if (data.code == 200) {
            this.$message.success("删除成功");
            this.getLabelList();
            this.getUserList();
            this.getAreaData();
          }
        });
      });
    },
    // 批量删除
    batchDelete () {
      // 获取选中的行
      const selectedRows = this.$refs.labelVxeTable.getCheckboxRecords();
      
      // 检查是否有选中项
      if (!selectedRows || selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的标签');
        return;
      }

      // 获取选中行的ID数组
      const ids = selectedRows.map((item) => item.id);

      this.$confirm(
        `确定删除选中的 ${selectedRows.length} 个标签吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: "/knowledgeLabel/batchDelete",
          method: "post",
          data: {
            deleteIds: ids
          },
        }).then(({ data }) => {
          if (data.code == 200) {
            this.$message.success("删除成功");
            // 刷新数据
            this.getLabelList();
            this.getUserList();
            this.getAreaData();
          } else {
            this.$message.error(data.msg || '删除失败');
          }
        }).catch(() => {
          this.$message.error('网络错误，请稍后重试');
        });
      }).catch(() => {
        // 用户取消删除
        this.$message.info('已取消删除');
      });
    },
    // 添加标签
    addElements(row, type) {
      this.elementsVisible = true;
      this.$refs["ruleForm"] && this.$refs["ruleForm"].resetFields();

      if (type == "edit") {
        this.elementsTitle = "修改标签";
        console.log(row, "修改dom");
        this.ruleForm.id = row.id;
        this.ruleForm.labelLevel = row.labelLevel;
        this.ruleForm.labelName = row.labelName;
        this.ruleForm.labelType = row.labelType;
        // 这是修改岗位标签时候
        if (row.labelLevel === 2) {
          this.ruleForm.area = row.parentId;
        } else if (row.labelLevel === 3) {
          // 这是标签类型的修改
          this.ruleForm.area = row.fieldId;
          this.ruleForm.post = [row.parentId];
          this.getPostData();
        }
      } else {
        this.elementsTitle = "新增标签";
      }
    },
    changeArea() {
      this.ruleForm.post = [];
      this.getPostData();
    },
    changeLabel() {
      this.ruleForm.area = "";
      this.ruleForm.post = [];
    },
    elementsConfirm() {
      console.log(this.ruleForm);
      // return
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // 需要判断是否是修改
          if (this.elementsTitle == "修改标签") {
            this.$http({
              url: "/knowledgeLabel/edit",
              method: "post",
              data: {
                labelLevel: this.ruleForm.labelLevel,
                labelName: this.ruleForm.labelName,
                labelType: this.$refs.labelLevel.selected.label,
                parentIds:
                  this.ruleForm.post.length > 0
                    ? this.ruleForm.post.join(",")
                    : this.ruleForm.area,
                id: this.ruleForm.id,
              },
            }).then(({ data }) => {
              this.$message.success("修改成功");
              this.elementsVisible = false;
              this.getLabelList();
              this.getUserList();
              this.getAreaData();
            });

            return;
          }
          this.$http({
            url: "/knowledgeLabel/add",
            method: "post",
            data: {
              labelLevel: this.ruleForm.labelLevel,
              labelName: this.ruleForm.labelName,
              labelType: this.$refs.labelLevel.selected.label,
              parentIds:
                this.ruleForm.post.length > 0
                  ? this.ruleForm.post.join(",")
                  : this.ruleForm.area,
            },
          }).then(({ data }) => {
            if (data.code == 200) {
              this.elementsVisible = false;
              this.getLabelList();
              this.$message.success("新增标签成功");
              // 需要重新将下拉列表重新获取下
              this.getUserList();
              this.getAreaData();
            } else {
              this.$message.warning(data.msg);
            }
          });
        }
      });
    },
    // 模版下载
    templateFn() {
      window.open(
        this.$config.VUE_APP_BASE_API +
          "/knowledgeLabel/template?token=" +
          localStorage.getItem("token"),
        "_self"
      );
      this.$message.success("下载成功");
    },
    resetSearch() {
      this.searchForm.fieldId = "";
      this.searchForm.name = "";
      this.searchForm.user = "";
      this.pageNo = 1;
      this.pageSize = 10;
      this.getLabelList();
    },
    searchBlur(){
      this.userForm.name = ""
      this.getUserList();
    },
    searchFocus(){
      this.userForm.name = ""
      this.searchForm.pageNumber = 1
      this.getUserList();
    },
    remoteMethod(e){
      console.log('eeee',e)
      this.userForm.name = e
      this.searchForm.pageNumber = 1
      this.userList = []
      this.getUserList();
    },
    //下拉框懒加载
    lazyloading() {
      console.log('55555')
    if( this.searchForm.pageNumber > this.searchForm.totalPage){
      return
    }
    this.searchForm.pageNumber++
    this.getUserList()
    },
    getUserList() {
      this.$http({
        url: "/knowledgeLabel/userList",
        method: "get",
        params: {
          pageSize:this.searchForm.pageSize,
          pageNumber:this.searchForm.pageNumber,
          name:this.userForm.name
        },
      }).then(({ data }) => {
        if (data.code == 200) {
          if(data.data.pageNumber == 1){
            this.userList = data.data.data;
          }else{
            this.userList = this.userList.concat(data.data.data == [] ? [] : data.data.data);
          }
          this.searchForm.pageSize = data.data.pageSize;
          this.searchForm.pageNumber = data.data.pageNumber;
          this.searchForm.totalPage = data.data.totalPage;
        }
      });
    },
    getAreaData() {
      this.$http({
        url: "/knowledgeLabel/field",
        method: "get",
        params: {},
      }).then(({ data }) => {
        if (data.code == 200) {
          this.areaList = data.data;
        }
      });
    },
    getPostData() {
      this.$http({
        url: "/knowledgeLabel/post",
        method: "get",
        params: {
          name: "",
          parentId: this.ruleForm.area,
        },
      }).then(({ data }) => {
        if (data.code == 200) {
          this.postList = data.data;
          this.$forceUpdate();
        }
      });
    },
    // 保存当前展开的节点状态
    saveExpandedNodes() {
      if (this.$refs.labelVxeTable) {
        const expandedNodes = this.$refs.labelVxeTable.getTreeExpandRecords();
        this.expandedNodeIds.clear();
        expandedNodes.forEach(node => {
          this.expandedNodeIds.add(node.id);
        });
      }
    },
    
    // 恢复展开的节点状态
    restoreExpandedNodes() {
      if (this.$refs.labelVxeTable && this.expandedNodeIds.size > 0) {
        // 延迟执行以确保DOM已更新
        this.$nextTick(() => {
          // 遍历表格数据，展开之前保存的节点
          const expandNodes = (nodes) => {
            nodes.forEach(node => {
              if (this.expandedNodeIds.has(node.id)) {
                this.$refs.labelVxeTable.setTreeExpand(node, true);
              }
              // 递归处理子节点
              if (node.children && node.children.length > 0) {
                expandNodes(node.children);
              }
            });
          };
          
          expandNodes(this.tableData);
        });
      }
    },
    
    getLabelList() {
      console.log('getLabelList====', this.pageNo)
      
      // 在重新加载数据前保存当前展开的节点状态
      this.saveExpandedNodes();
      
      this.$http({
        url: "/knowledgeLabel/list",
        method: "get",
        params: {
          fieldId: this.searchForm.fieldId,
          name: this.searchForm.name,
          pageNumber: this.pageNo,
          pageSize: this.pageSize,
          userId: this.searchForm.user,
        },
      }).then(({ data }) => {
        if (data.code == 200) {
          this.tableData = data.data.data;
          this.total = data.data.totalSize;
          this.isLoading = false
          
          // 数据加载完成后恢复展开的节点状态
          this.restoreExpandedNodes();
        }
      });
    },
    elementsVisibleClose() {
      this.elementsVisible = false;
    },
    // 批量导入
    batchImport() {
      // this.batchImportVisible = true
      this.$refs.importData.init();
    },
    // 批量导出
    batchExport() {
      let selectRecords = this.$refs.labelVxeTable.getCheckboxRecords();
      console.log("批量导出", selectRecords);
      if (selectRecords && selectRecords.length < 1) {
        this.$message.warning("请选择要导出的数据");
        return true;
      }
      let ids = selectRecords.map((item) => item.id);
      this.$utils.download({
        url: "/knowledgeLabel/export",
        method: "post",
        data: { ids },
      });
      /*this.$http({
        url: "/knowledgeLabel/export",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          ids: selectRecords.map(item => item.id)
        },
      }).then(({ data }) => {
        if (data.code == 200) {
          this.$message.success("导出成功");
        }
      })*/
    },
    batchImportConfirm() {
      this.batchImportVisible = false;
    },
    batchImportClose() {
      this.batchImportVisible = false;
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageNo = 1;
      this.getLabelList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNo = val;
      this.getLabelList();
    },
  },
};
</script>
<style lang="scss" scoped>
#contianer {
  width: 98%;
  background: white;
  border-radius: 10px;
  padding: 20px;
  margin: 1%;
  float: left;

  .screen_model {
    margin-bottom: 20px;
  }

  .el-select {
    width: 100%;
  }
}
</style>
